package com.example.wsServer;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.time.LocalDateTime;

/**
 * Author by admin, Email xx@xx.com, Date on 2020/5/19.
 * PS: Not easy to write code, please indicate.
 */
public class chatHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    //用于记录管理所有连接通道
    private static ChannelGroup clients= new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        //获取客户端传输过来的消息
        String content = msg.text();
        System.out.println(content+",客户端传送过来的");
        System.out.println(new TextWebSocketFrame("服务器接收到消息,"+ LocalDateTime.now()+"，消息为,"+content));
        //内置循环管理所有连接客户端
      clients.writeAndFlush(new TextWebSocketFrame("[服务器]接收到消息"+ LocalDateTime.now()+"，消息为,"+content));
//        clients.forEach(i->i.writeAndFlush(
//                new TextWebSocketFrame("服务器接收到消息"+ LocalDateTime.now()+"，消息为,"+content)));
    }
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        //添加通道给客户端，当客户段有连接时候
        System.out.println("有客户端连接");
        clients.add(ctx.channel());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        //当触发handlerRemoved 客户端关闭连接时，clients会自动移出handler
        //clients.remove(ctx.channel());
        System.out.println(ctx.channel().id().asLongText()+"客户端断开长id");
        System.out.println(ctx.channel().id().asShortText()+"客户端断开断id");
    }

}
